package juc.executors;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class ScheduledExecutorServiceExample1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
        //ScheduledFuture<?> future = executor.schedule(() -> System.out.println("i will be invoked"), 2, TimeUnit.SECONDS);
        //System.out.println(future.cancel(true));

        //ScheduledFuture<Integer> future = executor.schedule(() -> 2, 2, TimeUnit.SECONDS);
        //System.out.println(future.get());

        /**
         *  每隔2秒执行一次，但每个线程需要执行5秒，则会每隔5秒执行一次
         * period 2 seconds execute a task.
         * but the task spend 5 seconds actually
         * solution 1:(crontab/quartz/Control-M)
         * period first policy
         *
         */
        /*ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
            System.out.println("i am running");
            timeSleep(5);
        }, 1, 2, TimeUnit.SECONDS);*/

        final AtomicLong interval = new AtomicLong(0L);
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
            long currentTimeMillis = System.currentTimeMillis();
            if (interval.get() == 0) {
                System.out.printf("the first time trigger task at %d\n", currentTimeMillis);
            } else {
                System.out.printf("the actually spend %d\n", currentTimeMillis - interval.get());
            }
            interval.set(currentTimeMillis);
            timeSleep(5);
        }, 1, 2, TimeUnit.SECONDS);

    }

    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
